import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import Upload from 'rc-upload';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { publicityAdd, publicityUpdate, publicityDelete } from '../../services/api';
import { getArrFromObj, getToken, getCurrent } from '../../utils/utils';
import config from '../../common/config';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './announceList.less';

import uploadPng from '../../assets/upload.png';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const PAGE_STATUS_MAP = {
  '0': '无效',
  '1': '有效',
};

const PAGE_STATUS_ARR = getArrFromObj(PAGE_STATUS_MAP);

const PAGE_CATEGORY_MAP = {
  1: '新闻动态',
  2: '政策资讯',
  3: '知产干货',
  4: '关于我们',
};

const PAGE_CATEGORY_ARR = getArrFromObj(PAGE_CATEGORY_MAP);

const STATUS_MAP = {
  0: '暂存',
  1: '待审核',
  2: '审核通过',
  3: '审核不通过',
};

const STATUS_ARR = getArrFromObj(STATUS_MAP);

const PROJECT_TYPE_MAP = {
  0: '非战略咨询类',
  1: '战略咨询类',
};

const PROJECT_TYPE_ARR = getArrFromObj(PROJECT_TYPE_MAP);

const PAGE_SIZE = 10;

const DATE_PICKER_LOCALE = {
  lang: {
    locale: 'zh_CN',
    placeholder: 'Select date',
    rangePlaceholder: [''],
    today: '今天',
    now: 'Now',
    backToToday: 'Back to today',
    ok: 'Ok',
    clear: 'Clear',
    month: 'Month',
    year: 'Year',
    timeSelect: 'Select time',
    dateSelect: 'Select date',
    monthSelect: 'Choose a month',
    yearSelect: 'Choose a year',
    decadeSelect: 'Choose a decade',
    yearFormat: 'YYYY',
    dateFormat: 'M/D/YYYY',
    dayFormat: 'D',
    dateTimeFormat: 'M/D/YYYY HH:mm:ss',
    monthFormat: 'MMMM',
    monthBeforeYear: true,
    previousMonth: 'Previous month (PageUp)',
    nextMonth: 'Next month (PageDown)',
    previousYear: 'Last year (Control + left)',
    nextYear: 'Next year (Control + right)',
    previousDecade: 'Last decade',
    nextDecade: 'Next decade',
    previousCentury: 'Last century',
    nextCentury: 'Next century',
  },
  timePickerLocale: {
    placeholder: 'Select time',
  },
  dateFormat: 'YYYY-MM-DD',
  dateTimeFormat: 'YYYY-MM-DD HH:mm:ss',
  weekFormat: 'YYYY-wo',
  monthFormat: 'YYYY-MM',
};

@connect(({ announceList, loading }) => {
  return {
    announceList,
    loading: loading.models.announceList,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    id: null,

    title: null,
    projectType: 0,

    startTime: null,
    endTime: null,
    content: '',
  };

  componentDidMount() {
    this.init();
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'announceList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'announceList/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'announceList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      dispatch({
        type: 'announceList/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      levelRule: '',
      name: '',
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  async handleSave(e) {
    const { title, startTime, endTime, content } = this.state;
    if (!title) {
      return message.error('请填写标题');
    }

    if (!startTime) {
      return message.error('请选择公示开始时间');
    }

    if (!endTime) {
      return message.error('请选择公示结束时间');
    }

    if (!content) {
      return message.error('请填写内容');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const { id, title, projectType, startTime, endTime, content } = this.state;

    let response = {};
    if (id) {
      const params = { id, title, projectType, startTime, endTime, content: content.toHTML() };
      response = await publicityUpdate(params);
    } else {
      const params = { title, projectType, startTime, endTime, content: content.toHTML() };
      response = await publicityAdd(params);
    }

    if (response.code === 200) {
      this.setState({
        modalVisible: false,
      });

      this.init();
    } else {
      message.error(response.message);
    }
  }

  handleReply(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  handleSelectOnchange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleEdit(item) {
    this.setState({
      ...item,
      content: BraftEditor.createEditorState(item.content),
      modalVisible: true,
    });
  }

  async handleDelete(item) {
    const params = { id: item.id };
    const response = await publicityDelete(params);
    if (response.code === 200) {
      this.init();
    } else {
      message.error(response.message);
    }
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('title')(<Input placeholder="公示标题" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24} />

          <Col md={6} sm={24} />

          <Col md={6} sm={24} style={{ padding: '0' }}>
            <span style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                type="primary"
                onClick={this.handleShowModal.bind(this)}
                style={{ marginLeft: 5 }}
              >
                新增
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleEditorChange = editorState => {
    this.setState({
      content: editorState,
    });
  };

  uploadSuccess(res, field) {
    this.setState({
      [field]: res.data,
    });
  }

  uploadError(res, field) {
    debugger;
  }

  onDateChange(field, date, dateString) {
    this.setState({
      [field]: dateString + 'T00:00:00Z',
    });
  }

  render() {
    let { announceList: { data }, loading } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { selectedRows, modalVisible, imgOptions, coverUrl } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '公示标题',
        ellipsis: true,
        width: 100,
        dataIndex: 'title',
      },
      {
        title: '公示时间',
        dataIndex: 'unitsName',
        render: (val, item, index) => (
          <span>
            {moment(item.startTime).format('YYYY-MM-DD HH:mm:ss')} -{' '}
            {moment(item.endTime).format('YYYY-MM-DD HH:mm:ss')}
          </span>
        ),
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>{' '}
            <a href="javascript:;" onClick={this.handleDelete.bind(this, item)}>
              删除
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="公示列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              disableSelect={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          maskClosable={false}
          width="70%"
          title="新增公示"
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="标题">
                  <Input
                    style={{ width: '300px' }}
                    value={this.state.title}
                    onChange={this.handleOnchange.bind(this, 'title')}
                  />
                </Description>
              </DescriptionList>
            </Col>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="公示类型">
                  <Select
                    style={{ width: '200px' }}
                    placeholder=""
                    value={this.state.projectType + ''}
                    onChange={this.handleSelectOnchange.bind(this, 'projectType')}
                  >
                    {PROJECT_TYPE_ARR.map(item => {
                      return (
                        <Option key={item.id} value={item.id}>
                          {item.name}
                        </Option>
                      );
                    })}
                  </Select>
                </Description>
              </DescriptionList>
            </Col>
          </Row>
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="公示开始时间">
                  <DatePicker
                    size="middle"
                    style={{ width: '200px' }}
                    allowClear={false}
                    locale={DATE_PICKER_LOCALE}
                    placeholder="开始时间"
                    value={this.state.startTime ? moment(this.state.startTime) : null}
                    onChange={this.onDateChange.bind(this, 'startTime')}
                  />
                </Description>
              </DescriptionList>
            </Col>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="公示结束时间">
                  <DatePicker
                    size="middle"
                    style={{ width: '200px' }}
                    allowClear={false}
                    locale={DATE_PICKER_LOCALE}
                    placeholder="结束时间"
                    value={this.state.endTime ? moment(this.state.endTime) : null}
                    onChange={this.onDateChange.bind(this, 'endTime')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>

          <Divider orientation="left">详情</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList style={{ width: '100%' }} size="large" title="" col="1">
                <div style={{ border: '1px solid #ccc' }}>
                  <BraftEditor
                    value={this.state.content}
                    onChange={this.handleEditorChange.bind(this)}
                  />
                </div>
              </DescriptionList>
            </Col>
          </Row>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
